package cn.edu.hyit.hjq.volunteems.backend.service.impl;

import cn.edu.hyit.hjq.volunteems.backend.dto.reault.JsonResult;
import cn.edu.hyit.hjq.volunteems.backend.dto.request.RegisterRequest;
import cn.edu.hyit.hjq.volunteems.backend.mapper.UserMapper;
import cn.edu.hyit.hjq.volunteems.backend.pojo.User;
import cn.edu.hyit.hjq.volunteems.backend.service.RedisService;
import cn.edu.hyit.hjq.volunteems.backend.service.UserService;
import cn.edu.hyit.hjq.volunteems.backend.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtils jwtUtils;
    private final RedisService redisService;

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    public UserServiceImpl(UserMapper userMapper,
                       PasswordEncoder passwordEncoder,
                       JwtUtils jwtUtils,
                       RedisService redisService) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
        this.jwtUtils = jwtUtils;
        this.redisService = redisService;
    }

    @Override
    public JsonResult<?> registerUser(RegisterRequest registerRequest) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(registerRequest.getUsername()) != null) {
            // 使用Spring Boot的日志系统记录错误信息
            logger.warn("注册失败：用户名已存在，用户: {}", registerRequest.getUsername());
            return JsonResult.fail("用户名已存在");
        }

        // 创建用户对象，设置用户信息
        User user = new User();
        // 生成用户ID
        String userId = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
        user.setUserId(userId);
        // 加密密码并保存用户
        String encodedPassword = passwordEncoder.encode(registerRequest.getPassword());
        user.setPassword(encodedPassword);
        // 设置用户状态为未激活
        user.setStatus(0);
        // 其它信息
        user.setUsername(registerRequest.getUsername());
        user.setEmail(registerRequest.getEmail());
        user.setPhone(registerRequest.getPhone());
        user.setFullName(registerRequest.getFullName());
        // 设置创建时间和更新时间
        var time = LocalDateTime.now();
        user.setCreatedAt(time);
        user.setUpdatedAt(time);

        userMapper.insertUser(user);

        // 插入用户角色和用户技能
        userMapper.insertUserSkill(userId, registerRequest.getSkillIdList());
        // 插入用户角色
        userMapper.insertUserRole(userId, registerRequest.getRoleId());

        return JsonResult.success();
    }

    @Override
    public JsonResult<String> authenticateUser(String username, String password) {
        // 通过用户名和密码查询用户信息
        User user = userMapper.findByUsername(username);
        // 验证用户是否存在且密码匹配
        if (user == null || !passwordEncoder.matches(password, user.getPassword())) {
            // 使用Spring Boot的日志系统记录错误信息
            logger.error("登录失败：用户名或密码错误，用户: {}", username);
            return JsonResult.forbidden("用户名或密码错误");
        }

        // 生成 JWT Token
        String token = jwtUtils.generateToken(user.getUserId());
        // 使用 Redis Hash 存储多个字段
        redisService.setHashValue(token, "userId", user.getUserId());
        redisService.setHashValue(token, "role", user.getRole().getRoleName());
        redisService.setHashValue(token, "status", String.valueOf(user.getStatus()));
        redisService.expire(token, jwtUtils.getExpiration(), TimeUnit.MILLISECONDS);
        // 返回成功结果，包含Token
        return JsonResult.success(token);
    }

    @Override
    public JsonResult<List<User>> getUserList() {
        return JsonResult.success(userMapper.findAllUser());
    }

    @Override
    public JsonResult<String> ConvertUser(String userId) {
        User user =  userMapper.findByUserId(userId);
        if (user == null)
            return JsonResult.fail("用户不存在");
        Integer status = user.getStatus() == 0 ? 1 : 0;
        int rowsAffected =  userMapper.updateUserStatus(userId, status);
        if (rowsAffected > 0) {
            return JsonResult.success("更新用户状态成功");
        } else {
            return JsonResult.fail("更新用户状态失败");
        }
    }
}
